package com.eight.service;

import com.eight.feign.AccountFeign;
import com.eight.pojo.TbUser;
import com.eight.util.JWTTool;
import com.eight.util.WebUtil;
import com.eight.vo.ComResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: Van.Planifolia
 * @CreateTime: 2023-02-27  11:06
 * @Version: 1.0
 */
@Service("accountService")
public class AccountService {
    // 注入费恩接口
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录的操作
     *
     * @param username 用户id
     * @param password 用户密码
     * @return 登录结果
     */
    public ComResult getAccountBy(String username, String password) {
        // 根据账号密码查询用户信息
        TbUser tbUser = accountFeign.selectOne(username, password);

        // 如果用户为空返回错误信息
        if (tbUser == null) {
            return new ComResult(5001, "找不到客户的信息");
        } else if (tbUser.getStatus() != 0) {
            return new ComResult(4000, "用户当前被禁用，请联系管理员！");
        }
        // 否则就制作token并且返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        String token = JWTTool.generateToken(map);
        stringRedisTemplate.opsForValue().set(token, "");
        return new ComResult(2000, "登录成功", token);
    }

    /**
     * 用户登出的操作
     *
     * @return 登出的结果
     */
    public ComResult logout() {
        HttpServletRequest request = WebUtil.getRequest();
        Boolean accountToken = stringRedisTemplate.delete(request.getHeader("token"));
        if (Boolean.TRUE.equals(accountToken)) {
            return new ComResult(2000, "登出成功");
        } else {
            return new ComResult(5000, "登出失败");
        }
    }
}
